package com.ddwl.data.service;

import com.ddwl.common.util.BeanConverUtils;
import com.ddwl.schema.bo.data.ImageBo;
import com.ddwl.schema.bo.data.ImagePageBo;
import com.ddwl.schema.vo.data.ImageVo;
import com.ddwl.data.model.ImageLib;
import com.ddwl.data.repository.ImageLibRepository;
import com.ddwl.schema.bo.base.PageBo;
import com.ddwl.schema.vo.base.PageVo;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.Instant;
import java.util.List;

/**
 * @Author hemiaojun
 * @Date 2021/7/5 11:51
 */
@Service
@RequiredArgsConstructor
public class ImageLibService {

    private final ImageLibRepository imageLibRepository;



    public String uploadImg(ImageBo bo) {
        ImageLib il = BeanConverUtils.convertBean(bo, ImageLib.class);
        il.setGmtCreated(Instant.now());
        il = imageLibRepository.save(il);
        return il.getId();
    }

    public PageVo<ImageVo> page(PageBo<ImagePageBo> bo) {
        ImageLib param = BeanConverUtils.convertBean(bo.getParam(), ImageLib.class);
        Example<ImageLib> example = Example.of(param, ExampleMatcher.matchingAll().withIgnoreNullValues());
        if (!StringUtils.hasText(bo.getSort())) {
            bo.setSort("gmtCreated");
        }
        Sort sort = Sort.by(bo.isAsc() ? Sort.Direction.ASC : Sort.Direction.DESC, bo.getSort());
        PageRequest pageable = PageRequest.of(bo.getPage() - 1, bo.getPageSize(),sort);
        Page<ImageLib> page = imageLibRepository.findAll(example,pageable);
        List<ImageVo> imageVos = BeanConverUtils.convertBeanList(page.getContent(), ImageVo.class);
        return new PageVo<>(page.getTotalElements(), bo.getPage(), bo.getPageSize(), imageVos);
    }


}
